package com.abc.easyclaim;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.abc.bean.Case;
import com.abc.db.DBManager;
import com.abc.db.ExtDBHelper;
import com.abc.tool.Constants;
import com.abc.tool.XmlUtil;

public class MetroMenuActivity extends Activity implements OnClickListener,OnTouchListener {
	private static final String TAG = "jin";
	private LinearLayout photoLayout;
	private LinearLayout textLayout;
	private LinearLayout recordLayout;
	private LinearLayout locationLayout;
	private LinearLayout shareLayout;
	private LinearLayout exportLayout;
	private DBManager mgr =MainApplication.getMgr();
	
	private Case caze;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_metro_menu);
		//初始化监听器
		photoLayout=(LinearLayout)findViewById(R.id.metro_photo_layout);
		photoLayout.setOnClickListener(this);
		photoLayout.setOnTouchListener(this);
		textLayout=(LinearLayout)findViewById(R.id.metro_text_layout);
		textLayout.setOnClickListener(this);
		textLayout.setOnTouchListener(this);
		recordLayout=(LinearLayout)findViewById(R.id.metro_record_layout);
		recordLayout.setOnClickListener(this);
		recordLayout.setOnTouchListener(this);
		locationLayout=(LinearLayout)findViewById(R.id.metro_location_layout);
		locationLayout.setOnClickListener(this);
		locationLayout.setOnTouchListener(this);
		shareLayout=(LinearLayout)findViewById(R.id.metro_share_layout);
		shareLayout.setOnClickListener(this);
		shareLayout.setOnTouchListener(this);
		exportLayout=(LinearLayout)findViewById(R.id.metro_export_layout);
		exportLayout.setOnClickListener(this);
		exportLayout.setOnTouchListener(this);
		
		Log.e(TAG, "start onCreate~~~"); 
		//读取传过来的title;
		Intent intent=getIntent(); 
        Integer id=intent.getIntExtra("id",1);
        caze = mgr.queryCase(id);
		TextView titleTextView = (TextView) findViewById(R.id.metro_menu_title);
		titleTextView.setText(caze.getName());
		initPanel();
		//动态注册广播
		IntentFilter intentFilter = new IntentFilter();  
	    intentFilter.addAction(Constants.INTENT_REFRESH_METRO_MENU);  
	    //registerReceiver(mRefreshBroadcastReceiver, intentFilter); 
	}
	
	/**
	 * 界面初始化
	 */
	private void initPanel(){
		TextView photoNumTextView = (TextView) findViewById(R.id.metro_menu_photo_num);
		photoNumTextView.setText(""+mgr.countPhotos(caze.getId())+"张");
		TextView textNumTextView = (TextView) findViewById(R.id.metro_menu_text_num);
		textNumTextView.setText(""+mgr.countTexts(caze.getId())+"条");
		TextView recordNumTextView = (TextView) findViewById(R.id.metro_menu_record_num);
		recordNumTextView.setText(""+mgr.countRecords(caze.getId())+"条");
		TextView locationTextView = (TextView) findViewById(R.id.metro_menu_location);
		locationTextView.setText(""+caze.getAccidentAddress());
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.metro_menu, menu);
		return true;
	}

	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.metro_photo_layout:
			startActivity(new Intent(MetroMenuActivity.this, Camera.class));
			break;
		case R.id.metro_text_layout:
			textLayout.setBackgroundColor(Color.RED);
			startActivity(new Intent(MetroMenuActivity.this, TextListActivity.class));
			break;
		case R.id.metro_record_layout:
			startActivity(new Intent(MetroMenuActivity.this, RecordSound.class));
			break;
		case R.id.metro_location_layout:
			startActivity(new Intent(MetroMenuActivity.this, GprsMap.class));
			break;
		case R.id.metro_share_layout:                            //导入
			Intent intent=new Intent(MetroMenuActivity.this,ImportZip.class);       //进入导入文件选择界面
			startActivity(intent);
			break;
		case R.id.metro_export_layout:                         //导出
			Log.d("export", "my caseId :" +MainApplication.getCurrentCaseId());
			try {
				XmlUtil.pullCreateXml();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String photopath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/easyclaim/"+caze.getName()+"/photos";
			ArrayList<File> filelist=new ArrayList<File>();
			File photoFile=new File(photopath);
			if (!photoFile.exists()) {
				photoFile.mkdirs();
			}
			File[] photofiles=photoFile.listFiles();
	        for (int i = 0; i < photofiles.length; i++) {
				filelist.add(photofiles[i]);                  //加入照片文件
			}
	        String recordpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/easyclaim/"+caze.getName()+"/records";
	        File recordFile=new File(recordpath);
	        if (!recordFile.exists()) {
	        	recordFile.mkdirs();
			}
	        File[] recordfiles=recordFile.listFiles();
	        for (int i = 0; i < recordfiles.length; i++) {
				filelist.add(recordfiles[i]);                    //加入录音文件
			}

		    String zipFolder=Environment.getExternalStorageDirectory().getAbsolutePath()+"/easyclaim/export/";
			//导出文件夹等
			File folder=new File(zipFolder);         //创建保存导出文件的文件夹
			if (!folder.exists()) {
				folder.mkdirs();
			}
			String zippath=zipFolder+caze.getName()+".zip";
			File zipFile=new File(zippath);	
			ExtDBHelper helper=new ExtDBHelper(MetroMenuActivity.this);
			DatabaseDump ddDatabaseDump=new DatabaseDump(helper.getWritableDatabase(), zipFolder);
			ddDatabaseDump.exportData(filelist,zipFile ,caze.getId());    //与xls文件一起压缩
			
			new AlertDialog.Builder(MetroMenuActivity.this)   
	        .setTitle("提示")   
	        .setMessage("导出成功")   
	        .setPositiveButton("确定", null)   
	        .show();
			break;
		default:
			break;
		}
	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			v.setBackgroundColor(Color.GREEN);
			break;
		case MotionEvent.ACTION_UP:
			v.setBackgroundColor(this.getResources().getColor(R.color.sys_orange));
			break;
		default:
			break;
		}	
		return false;
	}
	
	@Override  
    protected void onDestroy() {  
        super.onDestroy();
       // unregisterReceiver(mRefreshBroadcastReceiver);
	}
	/*private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {  
		  
	      @Override  
	      public void onReceive(Context context, Intent intent) {  
	          String action = intent.getAction();  
	          if (action.equals(Constants.INTENT_REFRESH_METRO_MENU))  
	          {  
	              initPanel();  
	          }  
	      }  
	};  
*/	
	/**
	 * 返回该页面时刷新数据
	 */
	protected void onRestart() {  
        super.onRestart();  
        Log.e(TAG, "start onRestart~~~");  
        initPanel();
    }
}
